/*
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package botobjects;

import interfaces.BotObject;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.jibble.pircbot.Colors;

import tools.StringTools;
import tools.UtopiaTime;
import database.DBConnectionFactory;

/**
 * This class represents a target
 * 
 * 
 */
public class Target implements BotObject, Comparable<Target> {
   /**
    * Removes the specified target
    * 
    * @param args
    * @return true if the target was successfully deleted
    */
   public static boolean deleteFromDB(final String... args) {
	  boolean out = false;
	  if (args.length < 1)
		 return out;
	  PreparedStatement ps = null;
	  try {
		 ps = DBConnectionFactory.getConnectionHandler().getConnection().prepareStatement("DELETE FROM target WHERE name = ?");
		 ps.setString(1, args[0]);

		 if (ps.executeUpdate() == 1) {
			out = true;
		 }
	  } catch (final SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			ps.close();
		 } catch (final Exception e) {
		 }
	  }
	  return out;
   }

   /**
    * Returns a list of all targets
    * 
    * @return a List of Target objects
    */
   public static List<Target> getTargets() {
	  List<Target> out = new LinkedList<Target>();
	  PreparedStatement ps = null;
	  ResultSet rs = null;
	  try {
		 ps = DBConnectionFactory.getConnectionHandler().getConnection()
			   .prepareStatement("SELECT * FROM " + "target,province WHERE target.name = province.name");
		 rs = ps.executeQuery();

		 while (rs.next()) {
			out.add(new Target(rs.getString("message"), rs.getInt("nw"), rs.getInt("land"), rs.getString("target.name"), rs
				  .getString("target.loc"), "", false, rs.getTimestamp("addedtime").getTime()));
		 }
	  } catch (final SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			rs.close();
		 } catch (final Exception e) {
		 }
		 try {
			ps.close();
		 } catch (final Exception e) {
		 }
	  }
	  return out;
   }

   private String message = "";
   private int nw = 0;
   private int land = 0;
   private String name = "";
   private String kd = "";

   private double gbprot = 1.0;

   private Long addedTime = 0L;

   public Target(final String message, final Integer nw, final Integer land, final String name, final String kd, final String gb,
		 final boolean isWar, final Long addedTime) {
	  this.message = message;
	  this.nw = nw;
	  this.land = land;
	  this.name = name;
	  this.kd = kd;
	  if (gb.matches(".*(couple|little).*")) {
		 gbprot = isWar ? 1 : 0.9;
	  } else if (gb.matches(".*moderately.*")) {
		 gbprot = isWar ? 0.95 : 0.75;
	  } else if (gb.matches(".*heavily.*")) {
		 gbprot = isWar ? 0.9 : 0.4;
	  } else if (gb.matches(".*extremely.*")) {
		 gbprot = isWar ? 0.85 : 0.2;
	  }
	  this.addedTime = addedTime;
   }

   /**
    * Adjusts the land following a hit
    * 
    * @param adjust
    */
   public void adjustLand(final int adjust) {
	  gbprot -= 2.75 * adjust / land;
	  gbprot = Math.max(0, gbprot);
	  land -= adjust;
   }

   /**
    * Compares two targets based on their nw
    */
   @Override
   public int compareTo(final Target prov) {
	  if (nw < prov.getNw())
		 return -1;
	  else if (nw == prov.getNw())
		 return 0;
	  return 1;
   }

   /**
    * Two targets are considered equal if their names are, since province names are unique
    */
   @Override
   public boolean equals(final Object o) {
	  if (o instanceof Target)
		 return name.equals(((Target) o).getName());
	  return false;
   }

   public Long getAddedTime() {
	  return addedTime;
   }

   public double getGbprot() {
	  return gbprot;
   }

   @Override
   public List<String> getIRCOutput(final int outputType, final String... args) {
	  List<String> out = new LinkedList<String>();
	  if (StringTools.isNullOrEmpty(getMessage()) || StringTools.isNullOrEmpty(getName()) || StringTools.isNullOrEmpty(getKd())
			|| getAddedTime() == null)
		 return out;
	  out.add(Colors.RED + getName() + " " + getKd() + Colors.NORMAL + " >> " + Colors.BLUE + getMessage() + Colors.OLIVE
			+ " Added: " + Colors.BLUE + UtopiaTime.compareTimes(getAddedTime()) + " ago");
	  return out;
   }

   public String getKd() {
	  return kd;
   }

   public Integer getLand() {
	  return land;
   }

   public String getMessage() {
	  return message;
   }

   public String getName() {
	  return name;
   }

   public Integer getNw() {
	  return nw;
   }

   @Override
   public Map<String, Object> getRPCOutput(final int... includes) {
	  Map<String, Object> out = new HashMap<String, Object>();
	  if (StringTools.isNullOrEmpty(getMessage()) || StringTools.isNullOrEmpty(getName()) || StringTools.isNullOrEmpty(getKd())
			|| getAddedTime() == null)
		 return out;
	  out.put("Name", getName());
	  out.put("KD", getKd());
	  out.put("Land", getLand());
	  out.put("NW", getNw());
	  out.put("GB Prot", getGbprot());
	  out.put("Message", getMessage());
	  return out;
   }

   @Override
   public int hashCode() {
	  assert false : "hashCode not designed";
	  return 42; // any arbitrary constant will do
   }

   @Override
   public boolean saveToDB() {
	  boolean out = false;
	  if (StringTools.isNullOrEmpty(getMessage()) || StringTools.isNullOrEmpty(getName()) || StringTools.isNullOrEmpty(getKd())
			|| getAddedTime() == null)
		 return out;
	  PreparedStatement ps = null;
	  ResultSet rs = null;
	  try {
		 ps = DBConnectionFactory.getConnectionHandler().getConnection()
			   .prepareStatement("SELECT name FROM province WHERE name = ? AND kdloc = ?");
		 ps.setString(1, getName());
		 ps.setString(2, getKd());
		 rs = ps.executeQuery();

		 if (rs.next()) {
			deleteFromDB(getName());

			ps = DBConnectionFactory.getConnectionHandler().getConnection()
				  .prepareStatement("INSERT INTO target VALUES(?,?,?,true,?)");
			ps.setString(1, getName());
			ps.setString(2, getKd());
			ps.setString(3, getMessage());
			ps.setTimestamp(4, new Timestamp(getAddedTime()));
			if (ps.executeUpdate() == 1) {
			   out = true;
			}
		 }
	  } catch (final SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			rs.close();
		 } catch (final Exception e) {
		 }
		 try {
			ps.close();
		 } catch (final Exception e) {
		 }
	  }
	  return out;
   }

   public void setAddedTime(final Long addedTime) {
	  this.addedTime = addedTime;
   }

   public void setGbprot(final double gbprot) {
	  this.gbprot = gbprot;
   }

}
